package tech.$2306.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import tech.$2306.comment.dao.MessageDAO;
import tech.$2306.comment.exception.IPAddressMissException;
import tech.$2306.comment.model.dto.IPAddressDTO;
import tech.$2306.comment.model.dto.MessageDTO;
import tech.$2306.comment.model.vo.MessageVO;
import tech.$2306.comment.model.vo.input.MessageInput;
import tech.$2306.comment.service.MessageService;
import tech.$2306.comment.util.IPAddressUtil;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author Wangls
 * @since 2021-04-10 11:11
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private IPAddressUtil ipAddressUtil;

    @Resource
    private MessageDAO messageDAO;

    @Override
    public boolean saveMessage(MessageInput messageInput) {
        MessageDTO messageDTO = new MessageDTO();
        if (Strings.isBlank(messageInput.getMessagePostIp())) {
            throw new IPAddressMissException("IP未找到");
        }
        IPAddressDTO ipAddressDTO = ipAddressUtil.resolveIPAddress(messageInput.getMessagePostIp());
        BeanUtils.copyProperties(messageInput,messageDTO);
        messageDTO.setDeleted(0);
        messageDTO.setMessageTime(new Date());
        messageDTO.setMessageAddressProvince(ipAddressDTO.getProvince());
        messageDTO.setMessageAddressCity(ipAddressDTO.getCity());
        messageDTO.setMessageAddressCounty(ipAddressDTO.getCounty());
        messageDTO.setMessageIsp(ipAddressDTO.getIsp());
        return messageDAO.insert(messageDTO) > 0;
    }

    @Override
    public List<MessageVO> getMessageList() {
        List<MessageDTO> messageList = messageDAO.selectList(new QueryWrapper<MessageDTO>().orderByDesc("message_id"));
        if (CollectionUtils.isEmpty(messageList)) {
            return Lists.newArrayList();
        }
        List result = Lists.newArrayList();
        messageList.forEach((messageDTO)->{
            result.add(messageDTO.getMessageOutput());
        });
        return result;
    }
}
